using System.Security.Claims;
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

namespace MemoryCacheExample.Controllers;

/// <summary>
/// MemoryCache缓存操作
/// </summary>
[ApiController]
[Route("api/[controller]/")]
public class HomeController : ControllerBase
{
    /// <summary>
    /// 写入缓存
    /// </summary>
    [HttpPost("set")]
    public IActionResult Set()
    {
        MemoryCacheHelper.Set("hello", "hello world");
        return Ok("写入成功");
    }

    /// <summary>
    /// 写入缓存(10秒过期)
    /// </summary>
    [HttpPost("set/expires")]
    public IActionResult SetWithExpires()
    {
       _= MemoryCacheHelper.Set("hello", "hello world", TimeSpan.FromSeconds(10));
        return Ok("写入成功");
    }

    /// <summary>
    /// 写入缓存(10秒过期,滑动续期)
    /// </summary>
    [HttpPost("set/sliding")]
    public IActionResult SetWithSlid()
    {
        MemoryCacheHelper.Set("hello", "hello world", TimeSpan.FromSeconds(10),true);
        return Ok("写入成功");
    }
    

    /// <summary>
    /// 缓存读取
    /// </summary>
    [HttpGet("get")]
    public IActionResult Get()
    {
        return Ok(MemoryCacheHelper.Get("hello"));
    }


    /// <summary>
    /// 缓存数据是否存在
    /// </summary>
    [HttpGet("exists")]
    public IActionResult Exists()
    {
        return Ok(new {hello= MemoryCacheHelper.Exists("hello") ,world= MemoryCacheHelper.Exists("world") });
    }

    // /// <summary>
    // /// 读取所有键
    // /// </summary>
    // [HttpGet("keys")]
    // public IActionResult Keys()
    // {
    //     MemoryCacheHelper.Set("hello", "Hello");
    //     MemoryCacheHelper.Set("world", "World");
    //     
    //     return Ok(MemoryCacheHelper.GetAllKeys());
    // }

    /// <summary>
    /// 读取多个值
    /// </summary>
    [HttpGet("get/all")]
    public IActionResult GetAll()
    {
        MemoryCacheHelper.Set("hello", "Hello", TimeSpan.FromSeconds(3));
        MemoryCacheHelper.Set("world", "World", TimeSpan.FromSeconds(3));
        return Ok(MemoryCacheHelper.GetAll(new []{"hello","world"}));
    }
    

    record Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    /// <summary>
    /// 写入缓存并读取 - 泛型
    /// </summary>
    [HttpGet("generics")]
    public IActionResult Generics()
    {
        MemoryCacheHelper.Set("lucy", new Person { Id = 1001, Name = "Lucy" });
        return Ok(MemoryCacheHelper.Get<Person>("lucy"));
    }

    /// <summary>
    /// 写入缓存并读取 - 泛型集合
    /// </summary>
    [HttpGet("generics/all")]
    public IActionResult GenericsAll()
    {
        MemoryCacheHelper.Set("lucy", new Person { Id = 1001, Name = "Lucy" });
        MemoryCacheHelper.Set("jack", new Person { Id = 1002, Name = "Jack" });
        return Ok(MemoryCacheHelper.GetAll<Person>(new[]{"lucy","jack"}));
    }
    
}